import CustomError from "./CustomError";
import {setStorage} from "./Storage"
const QQ_MAP = require("../libs/qqmap-wx-jssdk.min.js");
const Config = {
    regions: "YQLBZ-HZEK5-CZEIO-Q7TLV-KJESS-LOBMX",
    locationDetail: "2MEBZ-N2OK4-P3RUA-DWGV3-CIDK2-SPB5J"
}

module.exports = {

    /*解析定位信息*/
    reverseGeocoder: function (location) {
        const qqMapSdk = new QQ_MAP({key: Config.locationDetail});
        return new Promise(function (resolve, reject) {
            qqMapSdk.reverseGeocoder({
                location: {latitude: location.latitude, longitude: location.longitude},
                success: function(detailRes) {
                    console.log(detailRes)
                    let landmark = detailRes.result.address_reference.landmark_l1 || detailRes.result.address_reference.landmark_l2
                    let locationDetail = {
                        address: detailRes.result.address,
                        location: detailRes.result.location,
                        province: detailRes.result.address_component.province,
                        city: detailRes.result.address_component.city,
                        district: detailRes.result.address_component.district,
                        town: detailRes.result.address_reference.town.title,
                        street: detailRes.result.address_component.street,
                        region: detailRes.result.address_component.province + ","
                            + detailRes.result.address_component.city + ","
                            + detailRes.result.address_component.district,
                        landmark: landmark.title
                    }
                    setStorage("config.locationDetail", locationDetail);
                    resolve(locationDetail);
                },
                fail: function(err) {
                    reject(new CustomError(err, "Location.reverseGeocoder"))
                }
            });
        })
    },
    /*获取城市列表*/
    getCityList: function () {
        const qqMapSdk = new QQ_MAP({key: Config.regions});
        return new Promise(function (resolve, reject) {
            qqMapSdk.getCityList({
                success: function (res) {
                    let newArr = [];
                    res.result[0].forEach(function (item) {
                        if (item.fullname.substring(item.fullname.length - 1) === "市") {
                            let hasIndex =  newArr.findIndex(function (x) {
                                return item.pinyin[0].substring(0,1).toUpperCase() === x.first
                            });
                            if (hasIndex >= 0) { //newArr中存在同一个字母的数据
                                newArr[hasIndex].list.push({
                                    id: item.id,
                                    fullName: item.fullname,
                                    pinyin: item.pinyin,
                                    location: item.location,
                                    shorthand: item.pinyin.map(function (x) {
                                        return x.substring(0,1)
                                    }).join("")
                                })
                            } else { //不存在
                                newArr.push({
                                    first: item.pinyin[0].substring(0,1).toUpperCase(),
                                    list: [{
                                        id: item.id,
                                        fullName: item.fullname,
                                        pinyin: item.pinyin,
                                        location: item.location,
                                        shorthand: item.pinyin.map(function (x) {
                                            return x.substring(0,1)
                                        }).join("")
                                    }]
                                })
                            }
                        }
                    });
                    res.result[1].forEach(function (item) {
                        if (item.fullname.substring(item.fullname.length - 1) !== "区") {
                            let hasIndex =  newArr.findIndex(function (x) {
                                return item.pinyin[0].substring(0,1).toUpperCase() === x.first
                            });
                            if (hasIndex >= 0) { //newArr中存在同一个字母的数据
                                newArr[hasIndex].list.push({
                                    id: item.id,
                                    fullName: item.fullname,
                                    pinyin: item.pinyin,
                                    location: item.location,
                                    shorthand: item.pinyin.map(function (x) {
                                        return x.substring(0,1)
                                    }).join("")
                                })
                            } else { //不存在
                                newArr.push({
                                    first: item.pinyin[0].substring(0,1).toUpperCase(),
                                    list: [{
                                        id: item.id,
                                        fullName: item.fullname,
                                        pinyin: item.pinyin,
                                        location: item.location,
                                        shorthand: item.pinyin.map(function (x) {
                                            return x.substring(0,1)
                                        }).join("")
                                    }]
                                })
                            }
                        }
                    });
                    newArr.sort(function (x, y) {
                        let a = x.first.toLowerCase();
                        let b = y.first.toLowerCase();
                        if (a < b) return -1;
                        if (a > b) return 1;
                        return 0;
                    });
                    resolve(newArr)
                },
                fail: function (err) {
                    reject(new CustomError(err, "Location.getCityList"))
                }
            });
        })
    },

    /*
    * 获取区域数据
    * */
    getRegions: async function () {
        const qqMapSdk = new QQ_MAP({key: Config.regions});
        return new Promise(function (resolve, reject) {
            qqMapSdk.getCityList({
                success: function (res) {
                    setStorage("regions", res.result)
                    resolve(res.result)
                },
                fail: function (err) {
                    reject(new CustomError(err, "Location.getRegions"))
                }
            })
        })
    },

    /*获取步数信息*/
    calculateDistance: function (data = {}) {
        const qqMapSdk = new QQ_MAP({key: Config.locationDetail});
        return new Promise(function (resolve, reject) {
            qqMapSdk.calculateDistance({
                //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
                //from参数不填默认当前地址
                //获取表单提交的经纬度并设置from和to参数（示例为string格式）
                mode: data.mode || "walking",
                from: data.from || "", //若起点有数据则采用起点坐标，若为空默认当前地址
                to: data.to, //终点坐标
                success: function (res) {
                    resolve(res.result.elements)
                },
                fail: function (err) {
                    reject(new CustomError(err, "Location.calculateDistance"))
                }
            });
        })
    }
}